#!/usr/bin/python2.5
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Munges RSS feeds to add correctly formatted GeoRSS points."""

import logging
import StringIO
import xml.dom
from xml.dom import minidom
from controllers import geocode


def FindChild(root, tag_name):
  for child in root.childNodes:
    if child.nodeType == xml.dom.Node.TEXT_NODE:
      continue
    if child.tagName == tag_name:
      return child
    else:
      continue
  else:
    raise ValueError('couldnt find %s child' % tag_name)


def MungeTasRSS(input_rss):
  """Convert points from GML to GeoRSS format."""
  doc = minidom.parseString(input_rss)
  rss = FindChild(doc, 'rss')

  channel = FindChild(rss, 'channel')
  for item in channel.childNodes:
    if item.nodeType == xml.dom.Node.TEXT_NODE:
      continue
    if item.tagName != 'item':
      continue
    where = FindChild(item, 'georss:where')
    if where:
      point = FindChild(where, 'gml:Point')
      if point:
        pos = FindChild(point, 'gml:pos')
        point = item.appendChild(doc.createElement('georss:point'))
        point.appendChild(pos.childNodes[0].cloneNode(deep=True))
  output_rss = StringIO.StringIO()
  doc.writexml(output_rss)
  return output_rss.getvalue()


def MungeRSS(input_rss, forcefetch=False):
  """Geocode Vic CFA RSS."""
  doc = minidom.parseString(input_rss)
  rss = FindChild(doc, 'rss')
  rss.setAttribute('xmlns:georss', 'http://www.georss.org/georss')

  channel = FindChild(rss, 'channel')
  for item in channel.childNodes:
    if item.nodeType == xml.dom.Node.TEXT_NODE:
      continue
    if item.tagName != 'item':
      continue
    title = FindChild(item, 'title')
    address = title.childNodes[0].data
    location = geocode.GetLocation(address.lower(), flush=forcefetch)
    if location:
      lat, longt, approx = location
      if lat is None or abs(lat) < 0.01:
        logging.info('got bogus location for %r', address)
      else:
        node = doc.createElement('georss:point')
        text = doc.createTextNode('%.5f %.5f' % (lat, longt))
        node.appendChild(text)
        item.appendChild(node)
        item.appendChild(doc.createTextNode('\n'))
        typ = doc.createElement('georss:featuretypetag')
        if approx:
          typ.appendChild(doc.createTextNode('area'))
        else:
          typ.appendChild(doc.createTextNode('point'))
        item.appendChild(typ)
        item.appendChild(doc.createTextNode('\n'))
  output_rss = StringIO.StringIO()
  doc.writexml(output_rss)
  return output_rss.getvalue()


if __name__ == '__main__':
  print MungeTasRSS(open('tas.xml').read())
